package com.qbw.app.module.common.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;

import com.lib.util.ResUtil;
import com.qbw.app.R;
import com.qbw.app.databinding.CommonFragmentMapBinding;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.core.base.BaseBottomDialogFragment;
import com.qbw.log.XLog;

import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.Constant.KEY_LAT;
import static com.qbw.app.Constant.KEY_LNG;

/**
 * @author qinbaowei
 * @date 2018/3/2
 * @email qbaowei@qq.com
 */

public class MapDialogFragment extends BaseBottomDialogFragment<CommonFragmentMapBinding> {

    private Listener mListener;

    private double mLat;
    private double mLon;

    public static MapDialogFragment createInstance(double lat, double lng) {
        Bundle args = new Bundle();
        MapDialogFragment fragment = new MapDialogFragment();
        args.putDouble(KEY_LAT, lat);
        args.putDouble(KEY_LNG, lng);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int onGetLayoutId() {
        return R.layout.common_fragment_map;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getArguments() : savedInstanceState;
        mLat = args.getDouble(KEY_LAT);
        mLon = args.getDouble(KEY_LNG);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onInit();
    }

    protected void onInit() {
        mBinding.imgBaidu.setVisibility(isInstallBaidu() ? View.VISIBLE : View.GONE);
        mBinding.tvBaidu.setVisibility(mBinding.imgBaidu.getVisibility());
        mBinding.imgGaode.setVisibility(isInstallGaode() ? View.VISIBLE : View.GONE);
        mBinding.tvGaode.setVisibility(mBinding.imgGaode.getVisibility());
        mBinding.imgGoogle.setVisibility(isInstallGoogle() ? View.VISIBLE : View.GONE);
        mBinding.tvGoogle.setVisibility(mBinding.imgGoogle.getVisibility());

        if (mBinding.imgBaidu.getVisibility() == View.GONE && mBinding.imgGaode.getVisibility() == View.GONE && mBinding.imgGoogle
                .getVisibility() == View.GONE) {
            UniversalToastUtil.showToast(R.string.not_install_all_map);
            dismiss();
        }

        mBinding.imgGoogle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClickGoogleMap();
                } else {
                    dismiss();
                    startGoogle();
                }
            }
        });
        mBinding.imgGaode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClickGaodeMap();
                } else {
                    dismiss();
                    startGaode();
                }
            }
        });
        mBinding.imgBaidu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClickBaiduMap();
                } else {
                    dismiss();
                    startBaidu();
                }
            }
        });
        mBinding.imgTencent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClickTencentMap();
                } else {

                }
            }
        });
        mBinding.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    public void setListener(Listener listener) {
        mListener = listener;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putDouble(KEY_LAT, mLat);
        outState.putDouble(KEY_LNG, mLon);
    }

    public interface Listener {
        void onClickGoogleMap();

        void onClickGaodeMap();

        void onClickBaiduMap();

        void onClickTencentMap();
    }

    /* 检查手机上是否安装了指定的软件
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    private boolean isInstallBaidu() {
        return isAvilible(getActivity(), "com.baidu.BaiduMap");
    }

    public void startBaidu() {
        if (isAvilible(getActivity(), "com.baidu.BaiduMap")) {//传入指定应用包名
            Intent intent = new Intent();
            String uriFormat = "baidumap://map/direction?destination=%f,%f&mode=driving";
            Gps gps = PositionUtil.gps84_To_Gcj02(mLat, mLon);
            if (gps != null) {
                gps = PositionUtil.gcj02_To_Bd09(gps.getWgLat(), gps.getWgLon());
            }
            if (gps == null) {
                gps = new Gps(mLat, mLon);
            }
            String uri = String.format(uriFormat, gps.getWgLat(), gps.getWgLon());
            XLog.d(uri);
            intent.setData(Uri.parse(uri));
            getActivity().startActivity(intent);
        } else {//未安装
            //market为路径，id为包名
            //显示手机上所有的market商店
            UniversalToastUtil.showToast(ResUtil.getString(R.string.not_install_baidu));
            //Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
            //intent = new Intent(Intent.ACTION_VIEW, uri);
            //context.startActivity(intent);
        }
    }

    private boolean isInstallGaode() {
        return isAvilible(getActivity(), "com.autonavi.minimap");
    }

    public void startGaode() {
        if (isAvilible(getActivity(), "com.autonavi.minimap")) {
            Intent intent = new Intent();
            Gps gps = PositionUtil.gps84_To_Gcj02(mLat, mLon);
            if (gps == null) {
                gps = new Gps(mLat, mLon);
            }
            intent.setData(Uri.parse("androidamap://navi?lat=" + gps.getWgLat() + "&lon=" + gps.getWgLon() + "&dev=0"));
            getActivity().startActivity(intent);
        } else {
            UniversalToastUtil.showToast(ResUtil.getString(R.string.not_install_gaode));
            //Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
            //intent = new Intent(Intent.ACTION_VIEW, uri);
            //context.startActivity(intent);
        }
    }

    private boolean isInstallGoogle() {
        return isAvilible(getActivity(), "com.google.android.apps.maps");
    }

    public void startGoogle() {
        if (isAvilible(getActivity(), "com.google.android.apps.maps")) {
            Gps gps = PositionUtil.gps84_To_Gcj02(mLat, mLon);
            if (gps == null) {
                gps = new Gps(mLat, mLon);
            }
            Uri gmmIntentUri = Uri.parse("google.navigation:q=" + gps.getWgLat() + "," + gps.getWgLon());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            getActivity().startActivity(mapIntent);
        } else {
            /*Toast.makeText(context, "您尚未安装谷歌地图", Toast.LENGTH_LONG).show();

            Uri uri = Uri.parse("market://details?id=com.google.android.apps.maps");
            intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);*/
            UniversalToastUtil.showToast(ResUtil.getString(R.string.not_install_google));
        }
    }

    public void setLat(double lat) {
        //lat:22.545837,longitude:113.965667
        mLat = lat;
        //mLat = 22.545837;
    }

    public void setLon(double lon) {
        mLon = lon;
        //mLon = 105.965667;
    }
}
